package com.lyc.day1101.demo5;

import java.util.Arrays;

/**
 * @author ：Xiaochen
 * @date ：Created in 2022/11/1 19:41
 * @description：
 * @modified By：
 * @version:
 */
public class TestSafe {
    private static String [] arr=new String[2];
    private static int index=0;
    private static Object lock =new Object();
    public static void main(String[] args) throws InterruptedException {

        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (lock) {
                    if (arr[index] == null) {
                        arr[index] = "hello";
                        index++;
                    }
                }
            }
        });
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (lock){
                if (arr[index]==null) {
                    arr[index] = "word";
                    index++;
                }
                }
            }
        });
        t1.start();
        t2.start();

        t1.join();
        t2.join();
        System.out.println(Arrays.toString(arr));
    }
}